package com.qfmy.web.app.service.impl.conmon;

import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.model.entity.common.UserTaskProgress;
import com.qfmy.web.app.mapper.common.UserTaskProgressMapper;
import com.qfmy.web.app.service.conmon.UserTaskProgressService;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Objects;


/**
 * @author 清风明月
 * @Package com.qfmy.web.app.service.impl.conmon
 * @date 2025/11/6
 * @description 签到任务
 */
@Service
public class UserTaskProgressServiceImpl implements UserTaskProgressService {

    /**
     * 注入mapper
     */
    @Autowired
    private UserTaskProgressMapper userTaskProgressMapper;


    /**
     * 提交签到任务
     * @param count
     * @param targetCount
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void commitUserTaskProgress(Integer count, Integer targetCount) {
        //获取用户id
        Long userId = getUserId();
        if (userId != null && userId < 0) {
            return;
        }
        //创建用户进度表
        UserTaskProgress userTaskProgress = new UserTaskProgress();
        userTaskProgress.setUserId(userId);
        userTaskProgress.setCompletedCount(count);
        userTaskProgress.setTargetCount(targetCount);
        //判断是否已经完成
        if (Objects.equals(count, targetCount)) {
            userTaskProgress.setIsCompleted(1);
        }else {
            userTaskProgress.setIsCompleted(0);
        }
        //设置任务进度时间
        userTaskProgress.setTaskDate(LocalDate.now());
        userTaskProgressMapper.insert(userTaskProgress);
    }

    /**
     * 获取用户id
     * @return
     */
    @Nullable
    @Contract(pure = true)
    private Long getUserId() {
        //获取用户id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断用户是否登录
        if (loginUser == null) {
            return 0L;
        }
        return loginUser.getUserId();
    }
}
